package com.hyjiacan.apps.audionly.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hyjiacan.apps.audionly.data.model.AudioParam
import com.hyjiacan.apps.audionly.data.model.TaskInfo
import com.hyjiacan.apps.audionly.data.model.VideoFile
import com.hyjiacan.apps.audionly.data.repository.TaskRepositoryImpl
import kotlinx.coroutines.launch
import java.io.File
import java.util.*

/**
 * 参数设置界面的ViewModel
 */
class ParamViewModel(application: Application) : AndroidViewModel(application) {
    // 音频格式 LiveData
    private val _selectedFormat = MutableLiveData<String>("mp3")
    val selectedFormat: LiveData<String> = _selectedFormat

    // 音频比特率 LiveData
    private val _selectedBitrate = MutableLiveData<Int>(128)
    val selectedBitrate: LiveData<Int> = _selectedBitrate

    // 输出文件名 LiveData
    private val _outputFilename = MutableLiveData<String>("")
    val outputFilename: LiveData<String> = _outputFilename

    // 视频文件路径
    private var videoPath: String? = null

    // 自定义存储路径 LiveData
    private val _customStoragePath = MutableLiveData<String?>(null)
    val customStoragePath: LiveData<String?> = _customStoragePath

    // 是否使用自定义存储路径
    private val _useCustomStoragePath = MutableLiveData<Boolean>(false)
    val useCustomStoragePath: LiveData<Boolean> = _useCustomStoragePath

    // 任务仓库
    private val taskRepository = TaskRepositoryImpl()

    /**
     * 设置视频文件路径
     */
    fun setVideoPath(path: String) {
        videoPath = path
        // 生成默认输出文件名，避免纯数字文件名
        val videoFile = File(path)
        val baseName = videoFile.nameWithoutExtension
        val format = _selectedFormat.value ?: "mp3"
        _outputFilename.value = "$baseName.$format"
    }

    /**
     * 更新输出文件名的扩展名
     */
    private fun updateOutputFilenameExtension(newFormat: String) {
        _outputFilename.value?.let {
            val nameWithoutExtension = it.substringBeforeLast('.', it)
            _outputFilename.value = "$nameWithoutExtension.$newFormat"
        }
    }

    /**
     * 设置音频格式
     */
    fun setFormat(format: String) {
        _selectedFormat.value = format
        // 更新输出文件名的扩展名
        updateOutputFilenameExtension(format)
    }

    /**
     * 设置音频比特率
     */
    fun setBitrate(bitrate: Int) {
        _selectedBitrate.value = bitrate
    }

    /**
     * 设置输出文件名
     */
    fun setOutputFilename(filename: String) {
        _outputFilename.value = filename
    }

    /**
     * 设置自定义存储路径
     */
    fun setCustomStoragePath(path: String?) {
        _customStoragePath.value = path
        _useCustomStoragePath.value = path != null
    }

    /**
     * 获取当前存储路径
     */
    fun getCurrentStoragePath(): String? {
        return if (_useCustomStoragePath.value == true) {
            _customStoragePath.value
        } else {
            null // 默认使用应用data目录
        }
    }

    /**
     * 创建音频提取任务
     */
    fun createExtractTask(): String {
        videoPath?.let {
            val audioParam = AudioParam(
                format = _selectedFormat.value ?: "mp3",
                bitRate = _selectedBitrate.value ?: 128
            )
            // 创建TaskInfo对象
            val taskInfo = TaskInfo(
                id = UUID.randomUUID().toString(),
                videoFile = VideoFile(
                    id = UUID.randomUUID().toString(),
                    name = File(it).name,
                    path = it,
                    duration = 0, // 实际应用中需要获取视频时长
                    size = File(it).length(),
                    format = File(it).extension
                ),
                audioParam = audioParam,
                status = TaskInfo.Status.PENDING,
                createTime = Date()
            )
            // 在协程中插入任务
            viewModelScope.launch {
                taskRepository.insertTask(taskInfo)
            }
            return taskInfo.id
        }
        return "" // 返回空字符串表示失败
    }
}